package com.tianhui.consignortwofei.mvp.ui.fragment.audit;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.fgs.common.other.CommonEvent;
import com.fgs.common.utils.CheckUtil;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseDataListFragment;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.interf.OnSearchClearListener;
import com.tianhui.consignortwofei.interf.OnSearchClickListener;
import com.tianhui.consignortwofei.mvp.contract.DriverContract;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.DriverInfo;
import com.tianhui.consignortwofei.mvp.presenter.DriverPresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.SearchActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.driver.DriverBankCardActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.driver.DriverRemarkActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.audit.driver.FrontAuditActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.bean.BusShuXin;
import com.tianhui.consignortwofei.mvp.ui.activity.carrier.CarrierListActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.DriverListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.xuexiang.xutil.security.Base64Utils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class DriverListFragment extends BaseDataListFragment<DriverContract.View, DriverContract.Presenter> implements DriverContract.View, OnSearchClickListener {

    private String mAuditStatus = "-1";
    private String mSearchKey;
    private boolean isNeedRefresh;
    private boolean isFirstVisible = true;
    private OnSearchClearListener onSearchClearListener;

    @BindView(R.id.rl_change_phone_layout)
    RelativeLayout rl_change_phone_layout;
    @BindView(R.id.layout_audit_bottom_saveButton)
    Button layout_audit_bottom_saveButton;
    @BindView(R.id.clet_old_phone_num)
    ClearEditText clet_old_phone_num;
    @BindView(R.id.clet_new_phone_num)
    ClearEditText clet_new_phone_num;


    public DriverListFragment() {
    }

    public DriverListFragment setOnSearchClearListener(OnSearchClearListener onSearchClearListener) {
        this.onSearchClearListener = onSearchClearListener;
        return this;
    }

    public static DriverListFragment newInstance(String auditStatus) {
        DriverListFragment driverListFragment = new DriverListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KeyValue.KEY_STATUS, auditStatus);
        driverListFragment.setArguments(bundle);
        return driverListFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_driver_list;
    }

    @Override
    protected DriverContract.View createView() {
        return this;
    }

    @Override
    protected DriverContract.Presenter createPresenter() {
        return new DriverPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new DriverListAdapter(getContext());
    }

    @Override
    protected void initListener() {
//        mAdapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                DriverInfo info = (DriverInfo) mAdapter.getAllData().get(position);
//                if (info != null) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(KeyValue.KEY_ID, info.id);
//                    openActivity(FrontAuditActivity.class, bundle);
//                }
//            }
//        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                DriverInfo info;
                switch (view.getId()) {
                    case R.id.item_driver_list_operateButton:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_DRIVER_INFO, info);
                            openActivity(DriverBankCardActivity.class, bundle);
                        }
                        break;
                    case R.id.item_driver_list_editButton:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_ID, info.id);
                            bundle.putInt(KeyValue.KEY_OPERATE, KeyValue.KEY_EDIT_OPERATE);
                            openActivity(FrontAuditActivity.class, bundle);
                        }
                        break;
                    case R.id.item_driver_list_auditButton:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_ID, info.id);
                            bundle.putInt(KeyValue.KEY_OPERATE, KeyValue.KEY_AUDIT_OPERATE);
                            openActivity(FrontAuditActivity.class, bundle);
                        }
                        break;
                    case R.id.item_driver_list_carrierButton:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_DRIVER_INFO, info);
                            openActivity(CarrierListActivity.class, bundle);
                        }
                        break;
                    case R.id.item_driver_list_remarkButton:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyValue.KEY_ID, info.id);
                            bundle.putInt(KeyValue.KEY_OPERATE, KeyValue.KEY_EDIT_OPERATE);
                            openActivity(DriverRemarkActivity.class, bundle);
                        }
                        break;
                    case R.id.item_driver_list_viewPasswordButton:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            viewPasswordDialog(info);
                        }
                        break;
                    case R.id.item_driver_list_changPhone:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {

                            initSave(info);
                            clet_old_phone_num.setText("");
                            clet_new_phone_num.setText("");
                            rl_change_phone_layout.setVisibility(View.VISIBLE);

                        }
//                        Toast.makeText(getContext(), "修改手机号"+info.drivertel, Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.item_driver_list_delete:
                        info = (DriverInfo) mAdapter.getAllData().get(position);
                        if (info != null) {
                            deleteDriver(info);
                        }
//                        Toast.makeText(getContext(), "删除司机", Toast.LENGTH_SHORT).show();
                        break;

                }
            }
        });

    }

    private void initSave(DriverInfo info) {
        String drivertel = info.drivertel;
        layout_audit_bottom_saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPhone = clet_old_phone_num.getText().toString();
                String newPhone = clet_new_phone_num.getText().toString();
                if (drivertel.equals(oldPhone)){
                    changePhone(oldPhone,newPhone);
                    rl_change_phone_layout.setVisibility(View.GONE);
                }else {
                    Toast.makeText(getContext(), "手机号与原手机号不一致", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private UserInfoModel mModel;
    private void changePhone(String oldPhone, String newPhone) {

        Map<String, String> map = new HashMap<>();
        map.put("oldmobile", oldPhone);
        map.put("mobile", newPhone);
        getPresenter().changeDriverPhone(map, true);
//        mModel.changedriverPhone(this, map, true, true, getContext().bindToLifecycle(), new ObserverResponseListener<CommonResponse>() {
//            @Override
//            public void onNext(CommonResponse commonResponse) {
//                showToast(commonResponse.getMsg());
//                if (commonResponse.getCode() == 20000) {
//                    ActivityManager.getInstance().finishAllActivity();
//                    openActivity(LoginActivityNew.class);
//                }
//            }
//
//            @Override
//            public void onError(ExceptionHandle.ResponseThrowable e) {
//                showToast(e.message);
//            }
//        });
    }

    //删除司机
    private void deleteDriver(DriverInfo info) {
        String driverno = info.driverno;
        new MaterialDialog.Builder(getContext())
                    .content("确定删除司机？")
                    .positiveText("取消")
                    .negativeText("确定")
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            Map<String, String> map = new HashMap<>();
                            map.put("driverNO", driverno);
                            getPresenter().deleteDriver(map, true);
                        }
                    })
                    .show();

    }



    private void viewPasswordDialog(DriverInfo info) {
        if (!TextUtils.isEmpty(info.driverpassword)) {
            String password = Base64Utils.decode(info.driverpassword);
            new MaterialDialog.Builder(getContext())
                    .content(password)
                    .positiveText("好的")
                    .negativeText("复制")
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            // 得到剪贴板管理器
                            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                            ClipData clipData = ClipData.newPlainText("mm", password);
                            // 把数据集设置（复制）到剪贴板
                            cm.setPrimaryClip(clipData);
                            showToast("已复制");
                        }
                    })
                    .show();
        } else {
            showToast("未找到密码");
        }
    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        Map<String, String> map = new HashMap<>();
        map.put("limit", "10");
        map.put("order", "desc");
        map.put("page", page + "");
        map.put("sort", "create_time");
        map.put("isaudit", mAuditStatus);
        if (!TextUtils.isEmpty(mSearchKey)) {
            if (CheckUtil.isMobileNO(mSearchKey)) {
                map.put("drivertel", mSearchKey);
            } else {
                map.put("drivername", mSearchKey);
            }
        }
        getPresenter().requestDriverList(map, isDialog);
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();

//        mModel = new UserInfoModel();

        if (bundle != null && !bundle.isEmpty()) {
            mAuditStatus = bundle.getString(KeyValue.KEY_STATUS, "-1");
        }

        rl_change_phone_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_change_phone_layout.setVisibility(View.GONE);
            }
        });


    }

    @Override
    public void onSearch(String searchKey) {
        this.mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    protected void onUserVisible() {
        super.onUserVisible();
        Log.e("fei","执行刷新1");
        if (getActivity() instanceof SearchActivity) {
            ((SearchActivity) getActivity()).setOnSearchClickListener(this);
        }
        if (isNeedRefresh && !isFirstVisible) {

            refreshData(true);
            isNeedRefresh = false;
        }
        if (isFirstVisible) {
            isFirstVisible = false;
            isNeedRefresh = false;
        }
    }

    @Override
    public void refreshOperate() {
        super.refreshOperate();

        mSearchKey = "";
        if (null != onSearchClearListener) {
            onSearchClearListener.onSearchClear();
        }
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);

        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_DRIVER_LIST:

                isNeedRefresh = true;
                break;
        }
    }







    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void shuXinList(BusShuXin event) {
        Log.e("fei","收到刷新3");
        this.mSearchKey = "";
        refreshData(true);
    }


//    @Override
//    public void onStart() {
//        super.onStart();
//        EventBus.getDefault().register(this);
//    }

//    @Override
//    public void onStop() {
//        EventBus.getDefault().unregister(this);
//        super.onStop();
//    }


}
